package com.y2w.gulimall.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.rabbitmq.client.Channel;
import com.y2w.gulimall.order.entity.OrderEntity;
import com.y2w.gulimall.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {
    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        long i = new Date().getTime() - orderEntity.getModifyTime().getTime();
        System.out.println("收到过期订单信息，准备关闭订单 ： " + orderEntity.getOrderSn());
        try {
            orderService.closeOrder(orderEntity);
            //手动调用支付宝收单
            //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
            //AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            //JSONObject bizContent = new JSONObject();
            //bizContent.put("trade_no", "2013112611001004680073956707");
            //request.setBizContent(bizContent.toString());
            //AlipayTradeCloseResponse response = alipayClient.execute(request);
            //if(response.isSuccess()){
            //    System.out.println("调用成功");
            //} else {
            //    System.out.println("调用失败");
            //}
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
